#import "HHLanguageService.h"
#import "NSBundle+HHLanguage.h"
#import <BCEventBus/BCEventBusKit.h>

@interface HHLanguageService ()

@end

@implementation HHLanguageService

///MARK: -service
+ (instancetype)service {
    static HHLanguageService *_service = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _service = [[self alloc] init];
    });
    return _service;
}

- (void)hh_setup {
    NSString *language = [self currentLanguageCode];
    [NSBundle setLanguage:language];
    if (![language isEqualToString:[self systemLanguagesCode]]) {
        // 强制设置系统语言
        [[NSUserDefaults standardUserDefaults] setObject:@[language] forKey:kHHLanguage_systemLanguageKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

///MARK: -change
- (void)hh_changeLanguage:(HHLanguageEnv)language {
    NSString *languageCode = @"zh-Hans";
    if (language == HHLanguageEnv_EN) {
        languageCode = @"en";
    }

    [NSBundle setLanguage:languageCode];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    // 保存用户选择
    [userDefault setObject:languageCode forKey:kHHLanguage_userLanguageKey];
    // 强制 设置系统语言
    [userDefault setObject:@[languageCode] forKey:kHHLanguage_systemLanguageKey];
    [userDefault synchronize];

    // 发送广播
    [BCPubProtocol(HHLanguageDelegate) withHandle:^(id <HHLanguageDelegate> _Nonnull target) {
        if ([target respondsToSelector:@selector(hh_languageDidChange:)]) {
            [target hh_languageDidChange:language];
        }
    }];
}

///MARK: -当前语言
- (HHLanguageEnv)hh_language {
    NSString *language = [self currentLanguageCode];
    if ([language hasPrefix:@"en"]) {
        return HHLanguageEnv_EN;
    } else {
        return HHLanguageEnv_ZH;
    }
}
- (NSString *)hh_serviceLanguage {
    NSString *language = [self currentLanguageCode];
    if ([language hasPrefix:@"en"]) {
        return @"en_US";
    } else {
        return @"hh_CN";
    }
}
/// web 语言
- (NSString *)hh_webLanguage {
    NSString *language = [self currentLanguageCode];
    if ([language hasPrefix:@"en"]) {
        return @"en";
    } else {
        return @"cn";
    }
}
- (NSString *)currentLanguageCode {
    // 先判断用户是否选择了语言
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *userLanguage = [userDefault objectForKey:kHHLanguage_userLanguageKey];
    if (userLanguage) {
        return userLanguage;
    }
    // 系统语言
    return [self systemLanguagesCode];
}

- (NSString *)systemLanguagesCode {
    NSString *sysLanguage = [[[NSUserDefaults standardUserDefaults] objectForKey:kHHLanguage_systemLanguageKey] firstObject];
    if ([sysLanguage hasPrefix:@"zh"]) {
        return @"zh-Hans";//简体中文
    } else if ([sysLanguage hasPrefix:@"en"]) {
        return @"en";//英语
    } else {
        return @"zh-Hans";//默认中文
    }
}

@end
